package cn.leftsite.juc.tools;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangjinqiang
 * @date 2019-06-03
 */

public class TryLock implements Runnable {
    private static final ReentrantLock lock1 = new ReentrantLock();
    private static final ReentrantLock lock2 = new ReentrantLock();

    int lock;

    public TryLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        if (lock == 1) {
            work(lock1, lock2);
        } else {
            work(lock2, lock1);
        }
    }

    private void work(ReentrantLock l1, ReentrantLock l2) {
        while (true) {
            if (l1.tryLock()) {
                try {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (l2.tryLock()) {
                        try {
                            System.out.println(Thread.currentThread().getId() + ": My Job done");
                            return;
                        } finally {
                            l2.unlock();
                        }
                    }

                } finally {
                    l1.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        TryLock r1 = new TryLock(1);
        TryLock r2 = new TryLock(2);

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();
    }
}
